<template>
  <view>
    <u-modal v-model="show" :content="content" @confirm="confirm" @cancel="show = false" :show-cancel-button="true"></u-modal>
    <u-search @search="search" :show-action="false" input-align="center" height="70" :clearabled="true" placeholder="请输入好友名称" v-model="keyword"></u-search>
    <u-empty v-if="isEmpty" text="您还没有添加任何好友" mode="list"></u-empty>
    <view v-if="isShow">
      <view class="message-list">
        <u-swipe-action :show="u.show" :index="i"
                        v-for="(u,i) in userList" :key="u.id"
                        @click="click" @open="open"
                        :options="options"
        >
          <view class="uni-swipe-action" @click="toMessageDetail(u.id,u.name,u.num)">
            <view class="item" :class="u.stick  ? 'stick' : ''">
              <block>
                <view class="item-left">
                  <avatar-group :isChat="false" :type="u.avatarType" :avatar="u.avatar" :text="u.name"></avatar-group>
                </view>
                <view class="item-middle">
                  <text class="title">{{ u.num }} {{ u.name }}</text>
                  <view class="message"><rich-text :nodes="u.msg"></rich-text></view>
                </view>
                <view class="item-right">
                  <view class="mark" v-if="u.count > 0">{{ u.count }}</view>
                  <view class="time">{{ u.gmtCreate | dateTimeFormat }}</view>
                </view>
              </block>
            </view>
          </view>
        </u-swipe-action>
      </view>
      <u-loadmore v-if="!isEmpty" :status="status" />
    </view>
  </view>
</template>

<script>
import avatarGroup from "@/components/avatar_group/avatar_group.vue"
import {timestampFormat} from "../../utils/date.js";
import { websocketObj } from '../../utils/websocket.js';
import {getChatSnapshotByUserId} from '../../utils/chat_utils.js';
import { networkStatus} from "../../utils/chat_utils";
import {DataContent, PrivateChatMsg} from "../../utils/chatObject";

export default {
  name: 'user-list',
  components: {
    avatarGroup
  },
  data() {
    return {
      isEmpty:false,
      keyword: '',
      options: [{
        text: "置顶",
        style: {
          backgroundColor: "#C7C6CD"
        }
      },
        {
          text: "删除",
          style: {
            backgroundColor: "#dd524d"
          }
        }
      ],
      userList: [],
      pageNum: 1,
      total: 0,
      status: '',
      show: false,
      content: '删除后还可从课程中添加，您确定要删除吗？',
      currentIndex: '',
      currentId: '',
      isShow: false
    }
  },
  onLoad() {
    networkStatus()
    uni.$emit("setVuexUserInfo",{user:null,isLoginPage: false});
    this.initial();
    websocketObj.sendMsg(new DataContent(1,new PrivateChatMsg(this.$store.getters.id,null,null,null,null),null));
    uni.$on("refreshUserChatSnapshot",this.refreshUserChatSnapshot);
    uni.$on("refreshUserChatSnapshotCount",this.refreshUserChatSnapshotCount);
    uni.$on("userListInit",this.initial);
  },
  onPullDownRefresh() {
    this.userList = [];
    this.initial();
    setTimeout(() => {
      uni.stopPullDownRefresh();
    },1000)
  },
  onReachBottom() {
    this.pageNum = ++ this.pageNum;
    this.status = 'loading';
    if((this.pageNum - 1) * 5 > this.total) {
      setTimeout(() => {
        this.status = 'nomore';
      }, 1000)
    }else {
      this.userListHandler(null);
      this.status = 'loadmore';
    }
  },
  methods: {
    initial(){
      // 初始化
      this.pageNum = 1;
      this.total = 0;
      this.keyword = '';
      this.userListHandler(null);
    },
    search(){
      // 搜索成功再显示
      this.isShow = false;
      this.pageNum = 1;
      if (this.$u.test.isEmpty(this.keyword)){
        this.$u.toast("搜索条件不能为空！");
        return;
      }
      this.$u.api.getChatUserByName(this.keyword).then(res => {
        if (res.data != null && res.data.length !== 0){
          this.userListBuilder(res.data);
        }
      })
    },
    async getChatUser(){
      return await this.$u.api.getChatUser(this.pageNum, this.$store.getters.id);
    },
    // 查询用户
    userListHandler(){
      this.getChatUser().then(res => {
        if (res.total === 0){
          this.isEmpty = true;
        }else {
          this.isEmpty = false;
          this.total = res.total;
          this.userListBuilder(res.data);
        }
      })
    },
    /**
     * 用户数据构造器，加入聊天快照消息和未读消息数量
     * @param data
     */
    userListBuilder(data){
      if (data != null && data.length !== 0){
        for (let user of data) {
          let v = getChatSnapshotByUserId(this.$store.getters.id,user.id);
          if (v != null){
            user['count'] = v.count;
            user['stick'] = v.stick;
            user['msg'] = v.msg;
            user['gmtCreate'] = v.gmtCreate;
            user['show'] = false;
          }else {
            user['count'] = 0;
            user['stick'] = false;
            user['msg'] =  [{
              children: [
                {
                  type: "text",
                  text: "[暂无消息]"
                }
              ],
              name: "div"
            }];
            user['show'] = false;
          }
        }
        if (this.pageNum > 1){
          // 第二页用拼接
          this.userList.concat(data);
        }else {
          // 第一页直接赋值
          this.userList = data;
          this.isShow = true;
        }
      }
    },
    // 刷新用户聊天快照
    refreshUserChatSnapshot(msg){
      let user = null;
      let idx = null;
      for (let i in this.userList){
        let item = this.userList[i];
        if (item.id === msg.uid){
          let pages = getCurrentPages();
          let page = pages.pop();
          // 如果是在聊天页面并且用户和消息ID相等时设置消息未读数为0
          if (page.route === 'pages/chat/chat' && page.options.id === msg.uid){
            item.count = 0;
          }else {
            item.count++;
          }
          item.msg = msg.msg;
          user = item;
          idx = i;
          break;
        }
      }
      if (user != null && idx != null){
        this.userList.splice(idx,1);
        this.userList.unshift(user);
      }
    },
    // 刷新用户未读消息数量为0
    refreshUserChatSnapshotCount(uid){
      let user = null;
      let idx = null;
      for (let i in this.userList){
        let item = this.userList[i];
        if (item.id === uid){
          item.count = 0;
          user = item;
          idx = i;
          break;
        }
      }
      if (user != null && idx != null){
        this.userList.splice(idx,1);
        this.userList.unshift(user);
      }
    },
    toMessageDetail(id,name,num) {
      this.$u.route({
        url: 'pages/chat/chat',
        params: {
          id: id,
          name: num + " " + name
        }
      })
    },
    click(index, index1) {
      if(index1 === 1) {
        this.currentIndex = index;
        this.currentId = this.userList[index].id;
        this.show = true;
      } else {
        // TODO 置顶
        this.$u.toast(`置顶暂未实现`);
      }
    },
    confirm(){
      this.$u.api.deleteFriend({myUid:this.$store.getters.id, friendId:this.currentId}).then(res => {
        if (res.code === 200){
          this.userList.splice(this.currentIndex, 1);
          this.$u.toast("删除成功");
        }
      })
    },
    open(index) {
      this.userList[index].show = true;
      this.$set(this.userList,index,this.userList[index]);
      this.userList.map((val, idx) => {
        if(index !== idx && this.userList[idx].show){
          this.userList[idx].show = false;
          this.$set(this.userList,idx,this.userList[idx]);
        }
      })
    }
  },
  filters:{
    dateTimeFormat: timestampFormat
  }
}
</script>

<style lang="scss">
.uni-swipe-action {
  width: 100%;
  overflow: hidden;
}

.item {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  padding: 10upx 16upx;
  background-color: #fff;
  border-bottom: 1px solid rgb(243, 243, 243);

  &.stick {
    background-color: rgba(243, 236, 221, .5);
  }

  .item-left {
    text-align: center;

    .image {
      width: 100rpx;
      height: 100rpx;
      border-radius: 50rpx;
      background-color: #eee;
    }

    .avatar {
      width: 100rpx;
      height: 100rpx;
      text-align: center;
      line-height: 100rpx;
      background: #4191ea;
      border-radius: 50%;
      overflow: hidden;

      .iconfont {
        width: 100rpx;
        height: 100rpx;
        text-align: center;
        line-height: 100rpx;
        color: #fff;
        font-size: 40rpx;
      }
    }
  }

  .item-middle {
    display: flex;
    flex: 1;
    flex-wrap: wrap;
    flex-direction: row;
    justify-content: flex-start;
    margin-left: 15rpx;
    overflow: hidden;

    .title {
      width: 100%;
      color: #000;
      font-family: "微软雅黑";
      font-weight: 400;
      font-size: 37rpx;
      height: 50rpx;
      line-height: 60rpx;
      overflow: hidden;
      /*自动隐藏文字*/
      text-overflow: ellipsis;
      /*文字隐藏后添加省略号*/
      white-space: nowrap;
      /**强制不换行*/
    }

    .message {
      width: 100%;
      font-family: "微软雅黑";
      color: #808080;
      height: 50rpx;
      font-weight: bold;
      line-height: 40rpx;
      font-size: 27rpx;
      overflow: hidden;
      /**自动隐藏文字*/
      text-overflow: ellipsis;
      /**文字隐藏后添加省略号*/
      white-space: nowrap;
      /**强制不换行*/
    }
  }

  .item-right {
    overflow: hidden;
    display: flex;
    flex-direction: column;
    align-items: center;
    font-size: 27rpx;
    font-weight: bold;

    .time {
      color: #808080;
      height: 60rpx;
      line-height: 60rpx;
    }

    .mark {
      background-color: #f74c31;
      line-height: 35rpx;
      text-align: center;
      font-size: 20rpx;
      min-width: 35rpx;
      min-height: 35rpx;
      border-radius: 18rpx;
      color: #fff;
    }
  }
}
</style>
